package com.carey.blog.repository.impl;

import java.util.logging.Logger;

import org.json.JSONObject;

import com.carey.blog.framework.latke.repository.gae.AbstractGAERepository;
import com.carey.blog.model.BlogSync;
import com.carey.blog.repository.BlogSyncManagementRepository;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

/**
 * Blog sync management Google App Engine repository.
 * 
 */
public final class BlogSyncMgmtGAERepository extends AbstractGAERepository
		implements BlogSyncManagementRepository {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(BlogSyncMgmtGAERepository.class.getName());

	@Override
	public String getName() {
		return BlogSync.BLOG_SYNC_MANAGEMENT;
	}

	@Override
	public JSONObject getByExternalBloggingSystem(
			final String externalBloggingSystem) {
		final Query query = new Query(getName());
		query.addFilter(BlogSync.BLOG_SYNC_EXTERNAL_BLOGGING_SYS,
				Query.FilterOperator.EQUAL, externalBloggingSystem);
		final PreparedQuery preparedQuery = getDatastoreService()
				.prepare(query);
		final Entity entity = preparedQuery.asSingleEntity();
		if (null == entity) {
			return null;
		}

		return entity2JSONObject(entity);
	}

	/**
	 * Gets the {@link BlogSyncMgmtGAERepository} singleton.
	 * 
	 * @return the singleton
	 */
	public static BlogSyncMgmtGAERepository getInstance() {
		return SingletonHolder.SINGLETON;
	}

	/**
	 * Private default constructor.
	 */
	private BlogSyncMgmtGAERepository() {
	}

	/**
	 * Singleton holder.
	 * 
	 */
	private static final class SingletonHolder {

		/**
		 * Singleton.
		 */
		private static final BlogSyncMgmtGAERepository SINGLETON = new BlogSyncMgmtGAERepository();

		/**
		 * Private default constructor.
		 */
		private SingletonHolder() {
		}
	}
}
